package com.sunyard.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Aspect
@Component
@Slf4j
public class WebLogAspect {


    private static final ThreadLocal<Long> context = new ThreadLocal<>();

    // 定义打印日志类
    public static void set(Long beforeTime) {
        context.set(beforeTime);

    }

    public static Long get() {
        return context.get();
    }

    @Pointcut("execution(public * com.sunyard.*.controller..*.*(..))")
    public void webLog() {

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 在controller层以外获取当前正在处理的请求，固定格式

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = request.getRemoteAddr();
//        String requesturl = request.getRequestURL();
        String method = request.getMethod();
        String params = null;
        if ("POST".equals(method) || "PUT".equals(method)) {
            Object[] args = joinPoint.getArgs();
            try {
                if (args.length > 0) {
                    params = args[0].toString();
                }
            } catch (Exception e) {
                log.warn("获取参数错误");
            }

        }
        if (String.valueOf(request.getRequestURL()).contains("acqRedirect")) {
            String uuid = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("jsrcu_uuid", uuid);
            cookie.setPath("/");
            if (String.valueOf(request.getRequestURL()).contains("js96008.com")) {
                cookie.setDomain("js96008.com");
            } else {
                log.info("测试环境,设置域名信息");
                cookie.setDomain("jsrcu.com");
            }
            HttpServletResponse response = servletRequestAttributes.getResponse();
            if (null != response) {
                response.addCookie(cookie);
            }
            MDC.put("uuid", uuid);
        }
        if (String.valueOf(request.getRequestURL()).contains("getAuth")
                || String.valueOf(request.getRequestURL()).contains("payPage")) {
            Cookie[] cookies = request.getCookies();
            if (null != cookies) {
                for (Cookie c : cookies) {
                    if ("jsrcu_uuid".equals(c.getName())) {
                        MDC.put("uuid", c.getValue());
                    }
                }
            }
        }
        set(System.currentTimeMillis());
        log.info("请求开始时间：{}", get());
        // 打印日志
        log.info("======================开始请求==================");
        log.info("URL:" + request.getRequestURL());
        log.info("方法:" + joinPoint.getSignature().toShortString());
        log.info("参数:" + params);
    }

    @After("webLog()")
    public void afterTime() {
        log.info("请求开始时间：{}", get());
        long betweenTime = System.currentTimeMillis() - get();
        log.info("耗时:" + betweenTime + " 毫秒");

    }

    @AfterReturning(returning = "rvt", pointcut = "execution(public * com.sunyard.*.controller..*.*(..))")
    public Object AfterExec(JoinPoint joinPoint, Object rvt) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        log.info("URL:" + request.getRequestURL());
        if (!request.getRequestURL().toString().contains("/organization/getOrgIds") && !request.getRequestURL().toString().contains("/popedom/findPopedoms")
                && !request.getRequestURL().toString().contains("/organization/newOrgTree") && !request.getRequestURL().toString().contains("/seePreQrCode")) {
            //pointcut是对应的注解类   rvt就是方法运行完之后要返回的值
            log.info("返回:" + JSON.toJSONString(rvt, SerializerFeature.WriteDateUseDateFormat));
        }
        log.info("======================请求结束==================");
        MDC.clear();
        return rvt;
    }


}
